<template>
  <component
    class="x-text"
    :is="tag">
      <div class="x-text-relative"></div>
      <div class="x-text-inner"
        :style="styles">
        <slot></slot>
      </div>
  </component>
</template>

<script>
  export default {
    componentName: 'EText',
    props: {
      tag: {
        type: String,
        default: 'div'
      },
      lineClamp: {
        type: Number,
        default: 1
      },
      height: {
        type: String
      }
    },
    computed: {
      styles () {
        if (this.lineClamp === 1) {
          return {
            'overflow': 'hidden',
            'white-space': 'nowrap'
          }
        } else if (this.lineClamp > 1) {
          return {
            'overflow': 'hidden',
            '-webkit-line-clamp': this.lineClamp,
            'line-clamp': this.lineClamp,
            'height': this.height,
            'display': '-webkit-box',
            'white-space': 'normal',
            '-webkit-box-orient': 'vertical'
          }
        }
        return {}
      }
    },
    mounted () {
      this.calc()
    },
    updated () {
      this.calc()
    },
    methods: {
      calc () {
        var requestIdleCallback = window.requestIdleCallback || window.mozRequestIdleCallback || window.msRequestIdleCallback || setTimeout
        var requestFrameAnimation = window.requestFrameAnimation || window.mozRequestFrameAnimation || window.msRequestFrameAnimation || setTimeout
        requestIdleCallback((deadline) => {
          let relativeNode = this.$el.querySelector('.x-text-relative')
          let innerNode = this.$el.querySelector('.x-text-inner')
          relativeNode.innerHTML = innerNode.innerHTML
          if (relativeNode.clientHeight > innerNode.clientHeight) {
            requestFrameAnimation(() => {
              this.$el.title = innerNode.innerText
            })
          }
        })
      }
    }
  }
</script>
